package com.uusee.crawler.util;

import org.apache.commons.lang.StringUtils;

public final class XmlUtils {
	private static final String LINE_SEPARATOR = System.getProperty("line.separator");
	private static final String SPACE = " ";
	private static final String FOUR_SPACE = "    ";
	
	public static String createHeader() {
		return createHeader("UTF-8");
	}
	
	public static String createHeader(String encode) {
		return "<?xml version=\"1.0\" encoding=\""+encode+"\" ?>"+LINE_SEPARATOR;
	}
	public static String createLine() {
		return LINE_SEPARATOR;
	}
	
	public static String createNodeStart(String nodeName) {
		return "<"+nodeName+">"+LINE_SEPARATOR;
	}
	
	public static String createNodeEnd(String nodeName) {
		return "</"+nodeName+">";
	}
	
	public static String createCdateNode(String nodeName,String nodeValue) {
		return createNode(nodeName,nodeValue,true);
	}
	
	public static String createNode(String nodeName,String nodeValue) {
		return createNode(nodeName,nodeValue);
	}
	
	public static String createNode(String nodeName,String nodeValue,boolean cdata) {	
		StringBuffer nodesb = new StringBuffer();
		if ( StringUtils.isNotEmpty(nodeValue)&&!"null".equals(nodeValue)) {
			nodesb.append(FOUR_SPACE);
			nodesb.append("<").append(nodeName).append(">");
			if (cdata) {
				nodesb.append("<![CDATA[");
				nodesb.append(nodeValue);
				nodesb.append("]]>");
			} else {
				nodesb.append(nodeValue);
			}
			nodesb.append("</").append(nodeName).append(">").append(LINE_SEPARATOR);
		}
		return nodesb.toString();
	}
	
	public static String createNodeInLine(String nodeName,String nodeValue,boolean cdata) {	
		StringBuffer nodesb = new StringBuffer();
		if ( StringUtils.isNotEmpty(nodeValue)) {
			nodesb.append("<").append(nodeName).append(">");
			if (cdata) {
				nodesb.append("<![CDATA[");
				nodesb.append(nodeValue);
				nodesb.append("]]>");
			} else {
				nodesb.append(nodeValue);
			}
			nodesb.append("</").append(nodeName).append(">");
		}
		return nodesb.toString();
	}
	
	
	public static String createNode(String nodeName,String propertyName,String propertyValue,String nodeValue,boolean cdata) {	
		StringBuffer nodesb = new StringBuffer();
		if ( StringUtils.isNotEmpty(nodeValue)&&!"null".equals(nodeValue)) {
			nodesb.append(FOUR_SPACE);
			nodesb.append("<").append(nodeName).append(" ").append(propertyName).append("=").append("\"").append(propertyValue).append("\"").append(">");
			if (cdata) {
				nodesb.append("<![CDATA[");
				nodesb.append(nodeValue);
				nodesb.append("]]>");
			} else {
				nodesb.append(nodeValue);
			}
			nodesb.append("</").append(nodeName).append(">").append(LINE_SEPARATOR);
		}
		return nodesb.toString();
	}
}
